package com.lineage.server.clientpackets;

import com.lineage.config.ConfigOther;
import com.lineage.echo.ClientExecutor;
import com.lineage.server.datatables.lock.ClanEmblemReading;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.L1CastleLocation;
import com.lineage.server.model.L1Character;
import com.lineage.server.model.L1Clan;
import com.lineage.server.model.L1Object;
import com.lineage.server.model.L1Teleport;
import com.lineage.server.model.L1War;
import com.lineage.server.serverpackets.S_CharVisualUpdate;
import com.lineage.server.serverpackets.S_CloseList;
import com.lineage.server.serverpackets.S_HelpMessage;
import com.lineage.server.serverpackets.S_MapID;
import com.lineage.server.serverpackets.S_Message_YN;
import com.lineage.server.serverpackets.S_OtherCharPacks;
import com.lineage.server.serverpackets.S_OwnCharPack;
import com.lineage.server.serverpackets.S_RemoveObject;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.S_War;
import com.lineage.server.serverpackets.S_Weather;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1EmblemIcon;
import com.lineage.server.timecontroller.server.ServerWarExecutor;
import com.lineage.server.world.World;
import com.lineage.server.world.WorldClan;
import com.lineage.server.world.WorldWar;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class C_War extends ClientBasePacket {
  private static final Log _log = LogFactory.getLog(C_War.class);
  
  public void start(byte[] decrypt, ClientExecutor client) {
    try {
      read(decrypt);
      L1PcInstance player = client.getActiveChar();
      String playerName = player.getName();
      String clanName = player.getClanname();
      int clanId = player.getClanid();
      if (!player.isCrown()) {
        player.sendPackets((ServerBasePacket)new S_ServerMessage(478));
      } else if (clanId == 0) {
        player.sendPackets((ServerBasePacket)new S_ServerMessage(272));
      } else {
        L1Clan clan = WorldClan.get().getClan(clanName);
        if (clan == null)
          return; 
        L1EmblemIcon emblemIcon = ClanEmblemReading.get().get(clan.getClanId());
        if (emblemIcon == null && !player.isGm()) {
          player.sendPackets((ServerBasePacket)new S_ServerMessage(812));
          return;
        } 
        if (player.getId() != clan.getLeaderId()) {
          player.sendPackets((ServerBasePacket)new S_ServerMessage(478));
          return;
        } 
        int type = readC();
        String tgname = readS();
        if (clanName.toLowerCase().equals(tgname.toLowerCase()))
          return; 
        L1Clan enemyClan = null;
        String enemyClanName = null;
        Collection<L1Clan> allClans = WorldClan.get().getAllClans();
        Iterator<L1Clan> iter = allClans.iterator();
        while (iter.hasNext()) {
          L1Clan checkClan = iter.next();
          if (checkClan.getClanName().toLowerCase().equals(tgname.toLowerCase())) {
            enemyClan = checkClan;
            enemyClanName = checkClan.getClanName();
            break;
          } 
        } 
        if (enemyClan == null) {
          if (tgname.equals(" "))
            war_castle(player, clan, (L1Clan)null, type); 
          return;
        } 
        boolean inWar = false;
        List<L1War> warList = WorldWar.get().getWarList();
        if (enemyClan.getCastleId() == 0) {
          Iterator<L1War> iterator = warList.iterator();
          while (iterator.hasNext()) {
            L1War war = iterator.next();
            if (war.checkClanInWar(clanName)) {
              if (type == 0) {
                player.sendPackets((ServerBasePacket)new S_ServerMessage(234));
                return;
              } 
              inWar = true;
              break;
            } 
          } 
        } 
        if (!inWar && (type == 2 || type == 3))
          return; 
        if (clan.getCastleId() != 0) {
          if (type == 0) {
            player.sendPackets((ServerBasePacket)new S_ServerMessage(474));
            return;
          } 
          if (type == 2 || type == 3)
            return; 
        } 
        if (enemyClan.getCastleId() == 0 && player.getLevel() <= ConfigOther.clanLeaderlv) {
          player.sendPackets((ServerBasePacket)new S_ServerMessage("等级" + ConfigOther.clanLeaderlv + "以下的君主无法宣战"));
          return;
        } 
        if (enemyClan.getCastleId() != 0) {
          war_castle(player, clan, enemyClan, type);
          return;
        } 
        if (ServerWarExecutor.get().checkCastleWar() > 0) {
          player.sendPackets((ServerBasePacket)new S_HelpMessage("\\fS攻城战期间，暂停血盟宣战。"));
          return;
        } 
        boolean enemyInWar = false;
        Iterator<L1War> iterator2 = warList.iterator();
        while (iterator2.hasNext()) {
          L1War war2 = iterator2.next();
          if (war2.checkClanInWar(enemyClanName)) {
            switch (type) {
              case 0:
                player.sendPackets((ServerBasePacket)new S_ServerMessage(236, enemyClanName));
                return;
              case 2:
              case 3:
                if (!war2.checkClanInSameWar(clanName, enemyClanName))
                  return; 
                break;
            } 
            enemyInWar = true;
            break;
          } 
        } 
        if (!enemyInWar && (type == 2 || type == 3))
          return; 
        L1PcInstance enemyLeader = World.get().getPlayer(enemyClan.getLeaderName());
        if (enemyLeader == null) {
          player.sendPackets((ServerBasePacket)new S_ServerMessage(218, enemyClanName));
          return;
        } 
        switch (type) {
          case 0:
            enemyLeader.setTempID(player.getId());
            enemyLeader.sendPackets((ServerBasePacket)new S_Message_YN(217, clanName, playerName));
            break;
          case 2:
            enemyLeader.setTempID(player.getId());
            enemyLeader.sendPackets((ServerBasePacket)new S_Message_YN(221, clanName));
            break;
          case 3:
            enemyLeader.setTempID(player.getId());
            enemyLeader.sendPackets((ServerBasePacket)new S_Message_YN(222, clanName));
            break;
        } 
        return;
      } 
      return;
    } catch (Exception exception) {
    
    } finally {
      over();
    } 
  }
  
  private void war_castle(L1PcInstance player, L1Clan clan, L1Clan enemyClan, int type) {
    try {
      if (player.getLevel() < ConfigOther.clanLeaderlv) {
        player.sendPackets((ServerBasePacket)new S_ServerMessage("等级" + ConfigOther.clanLeaderlv + "以下的君主无法宣战"));
        return;
      } 
      L1EmblemIcon emblemIcon = ClanEmblemReading.get().get(clan.getClanId());
      if (emblemIcon == null && !player.isGm()) {
        player.sendPackets((ServerBasePacket)new S_ServerMessage(812));
        return;
      } 
      String clanName = player.getClanname();
      if (enemyClan == null) {
        L1Object object = World.get().findObject(player.getTempID());
        if (object instanceof com.lineage.server.model.Instance.L1NpcInstance) {
          int id = L1CastleLocation.getCastleIdByArea((L1Character)object);
          if (ServerWarExecutor.get().isNowWar(id)) {
            L1PcInstance[] clanMember = clan.getOnlineClanMember();
            int k = 0;
            while (k < clanMember.length) {
              clanMember[k].sendPackets((ServerBasePacket)new S_War(1, clanName, "NPC"));
              k++;
            } 
            player.sendPackets((ServerBasePacket)new S_CloseList(player.getId()));
            k = 0;
            while (k < clanMember.length) {
              if (L1CastleLocation.checkInWarArea(id, (L1Character)clanMember[k])) {
                L1PcInstance[] clanMembers = clan.getOnlineClanMember();
                L1PcInstance[] array;
                int n = (array = clanMembers).length;
                int i = 0;
                while (i < n) {
                  L1PcInstance clanMember2 = array[i];
                  if (clanMember2.getId() != player.getId() && !clanMember2.isFishing() && 
                    !clanMember2.isPrivateShop()) {
                    L1Teleport.teleport(clanMember2, 33427, 32816, (short)4, 5, true);
                    clan.sendPacketsAll((ServerBasePacket)new S_ServerMessage("\\aD宣战:系统强制驱离旗子范围内本血盟玩家"));
                  } 
                  if (clanMember2.isDead())
                    restartPlayer(clanMember2, 33064, 32772, (short)4); 
                  i++;
                } 
              } 
              k++;
            } 
          } else {
            if (type == 0)
              player.sendPackets((ServerBasePacket)new S_ServerMessage(476)); 
            player.sendPackets((ServerBasePacket)new S_CloseList(player.getId()));
          } 
        } 
        return;
      } 
      String enemyClanName = enemyClan.getClanName();
      if (WorldWar.get().isWar(clan.getClanName(), enemyClanName)) {
        player.sendPackets((ServerBasePacket)new S_ServerMessage(234));
        return;
      } 
      int castle_id = enemyClan.getCastleId();
      if (ServerWarExecutor.get().isNowWar(castle_id)) {
        L1PcInstance[] clanMember = clan.getOnlineClanMember();
        int k = 0;
        while (k < clanMember.length) {
          if (L1CastleLocation.checkInWarArea(castle_id, (L1Character)clanMember[k])) {
            L1PcInstance[] clanMembers = clan.getOnlineClanMember();
            L1PcInstance[] array;
            int n = (array = clanMembers).length;
            int i = 0;
            while (i < n) {
              L1PcInstance clanMember2 = array[i];
              if (clanMember2.getId() != player.getId() && !clanMember2.isFishing() && 
                !clanMember2.isPrivateShop()) {
                L1Teleport.teleport(clanMember2, 33064, 32772, (short)4, 5, true);
                clan.sendPacketsAll((ServerBasePacket)new S_ServerMessage("\\aD宣战:系统强制驱离旗子范围内本血盟玩家"));
              } 
              if (clanMember2.isDead())
                restartPlayer(clanMember2, 33064, 32772, (short)4); 
              i++;
            } 
          } 
          k++;
        } 
        List<L1War> warList = WorldWar.get().getWarList();
        boolean enemyInWar = false;
        Iterator<L1War> iterator = warList.iterator();
        while (iterator.hasNext()) {
          L1War war = iterator.next();
          if (war.checkClanInWar(enemyClanName)) {
            if (type == 0) {
              war.declareWar(clanName, enemyClanName);
              war.addAttackClan(clanName);
              player.sendPackets((ServerBasePacket)new S_CloseList(player.getId()));
            } else if (type == 2 || type == 3) {
              if (!war.checkClanInSameWar(clanName, enemyClanName))
                return; 
              if (type == 2) {
                war.surrenderWar(clanName, enemyClanName);
              } else if (type == 3) {
                war.ceaseWar(clanName, enemyClanName);
              } 
            } 
            enemyInWar = true;
            break;
          } 
        } 
        if (!enemyInWar && type == 0) {
          L1War war = new L1War();
          war.handleCommands(1, clanName, enemyClanName);
          player.sendPackets((ServerBasePacket)new S_CloseList(player.getId()));
        } 
      } else {
        if (type == 0)
          player.sendPackets((ServerBasePacket)new S_ServerMessage(476)); 
        player.sendPackets((ServerBasePacket)new S_CloseList(player.getId()));
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  public void restartPlayer(L1PcInstance pc, int locx, int locy, short mapid) {
    pc.removeAllKnownObjects();
    pc.broadcastPacketAll((ServerBasePacket)new S_RemoveObject((L1Object)pc));
    pc.setCurrentHp(pc.getLevel());
    pc.set_food(40);
    pc.setDead(false);
    pc.setStatus(0);
    World.get().moveVisibleObject((L1Object)pc, mapid);
    pc.setX(locx);
    pc.setY(locy);
    pc.setMap(mapid);
    pc.sendPackets((ServerBasePacket)new S_MapID(pc, pc.getMapId(), pc.getMap().isUnderwater()));
    pc.broadcastPacketAll((ServerBasePacket)new S_OtherCharPacks(pc));
    pc.sendPackets((ServerBasePacket)new S_OwnCharPack(pc));
    pc.sendPackets((ServerBasePacket)new S_CharVisualUpdate(pc));
    pc.startHpRegeneration();
    pc.startMpRegeneration();
    pc.sendPackets((ServerBasePacket)new S_Weather(World.get().getWeather()));
    pc.stopPcDeleteTimer();
    if (pc.getHellTime() > 0)
      pc.beginHell(false); 
  }
  
  public String getType() {
    return getClass().getSimpleName();
  }
}
